-module(echoserver).
-compile(export_all).

-define(TCP_OPTIONS, [binary, {packet, line}, {reuseaddr, true}, {active, true}]).

start() ->
	{ok, Listener} = gen_tcp:listen(2345, ?TCP_OPTIONS),
	spawn(fun() -> server_loop(Listener) end).

server_loop(Listener) ->
    io:fwrite("Socket:~p listening on port:~p~n", [Listener, inet:port(Listener)]),
	{ok, Socket} = gen_tcp:accept(Listener),
	io:format("Socket accepted: ~p~n", [Socket]),
	spawn(fun() -> server_loop(Listener) end),
	loop(Socket).
	
loop(Socket) ->
    receive
	    {tcp, Socket, Packet} ->
            Response = io_lib:format("~p: ~s~n", [{date(), time()}, Packet]),
	        gen_tcp:send(Socket, Response),
	        loop(Socket);
	    {tcp_closed, Socket} ->
	        io:format("Client connection closed~n"),
	        gen_tcp:close(Socket)
    end.

